﻿#include "server.h"
#include "clientthread.h"
#include <QThread>
Server::Server(QObject *parent) : QTcpServer(parent)
{
    this->listen(QHostAddress::Any,quint16(8800));
}

void Server::incomingConnection(qintptr socketDescriptor)
{
    qDebug()<<"has new client connect("<<socketDescriptor<<")";
    socketList.append(socketDescriptor);
    QThread *thread=new QThread();
    ClientThread  *client=new ClientThread(socketDescriptor);
    connect(client,&ClientThread::started,client,&ClientThread::run,Qt::QueuedConnection);
    connect(thread,SIGNAL(finished()),this,SLOT(deleteLater()));
    connect(client,&ClientThread::TCPConnect,this,&Server::Connect);
    connect(client,&ClientThread::senddata,this,&Server::receive);
    connect(client,&ClientThread::sig_heart,this,&Server::receive_heart);
    connect(this,&Server::Senddata,client,&ClientThread::sendData);
    client->moveToThread(thread);
    thread->start();
    emit client->started();
}

void Server::receive(QString arr)
{
    //DCDC数据分流
    QString DCDC1_1 = arr.mid(4,16);
    QString DCDC1_2 = arr.mid(20,16);
    //485数据1分流
    QString rs485data1 = arr.mid(36,18);
    //485数据1分流
    QString rs485data2 = arr.mid(54,12);

    emit SIGDC1_1("1"+DCDC1_1);
    emit SIGDC1_2("2"+DCDC1_2);
    emit SIGRs4851(rs485data1);
    emit SIGRs4852(rs485data2);
    qDebug()<<arr;
}

void Server::receive_heart(QString arr)
{
    emit sigdata(arr);
}

void Server::Connect(bool bo)
{
    emit SIGCon(bo);
}

void Server::SendTCP(QString da)
{
    emit Senddata(da);
    //qDebug()<<da;
}
